package com.sirui.cloud.identity.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint(value = "/im")
public class WebSocket {

	private Logger logger = LoggerFactory.getLogger(WebSocket.class);

	private Map<String, Session> sessionMap = new HashMap<>();

	@OnOpen
    public void onOpen(Session session, @PathParam(value = "token") String token){
		logger.info("{sessionId:{}, token: {}}", session.getId());
		sessionMap.put(session.getId(), session);
	}
	
	@OnClose
	public void onClose(Session session) {
		logger.info("{sessionId:{}}", session.getId());
		sessionMap.remove(session.getId());
	}
	
	@OnMessage
	public void onMsg(Session session, String msg) {
		logger.info("{sessionId:{}, msg:{}}", session.getId(), msg);
		try {
			session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			logger.error("send msg error.", e);
		}
	}
	
	@OnError
	public void onError(Session session, Throwable e) {
		logger.error("", e);
	}
}
